<?php

namespace app\index\controller;

use app\index\job\JobActivity;
use think\Cache;
use think\Controller;
use think\Db;
use think\Loader;
use think\Queue;
use think\Request;
use think\Validate;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\TemplateProcessor;
use PhpOffice\PhpWord\Settings;

class Api extends Controller
{
    public function generateContract()
    {
        // 动态数据
        $name = '张三';            // 可以从数据库或请求参数获取
        $phone = '13812345678';

        // 创建一个新的PHPWord对象
        $phpWord = new PhpWord();

        // 创建一个新的Section
        $section = $phpWord->addSection();

        // 添加标题
        $section->addTitle('红娘与平台合同', 1);

        // 添加文本
        $section->addText("尊敬的 ________________________，");
        $section->addText("您已与本平台达成协议，以下为您的联系方式：");
        $section->addText("手机号：{$phone}");
        $section->addText("请核对以上信息。");

        // 添加签名区域
        $section->addTextBreak(2); // 空行
        $section->addText("签名：________________________");
        $section->addTextBreak(2); // 空行
        $section->addText("日期：________________________");

        // 生成的文件名
        $fileName = "contract_{$name}.docx";

        // 设置 HTTP 响应头，下载 Word 文件
        header('Content-Type: application/msword');
        header('Content-Disposition: attachment;filename="' . $fileName . '"');
        header('Cache-Control: max-age=0');

        // 创建Word文件
        $objWriter = IOFactory::createWriter($phpWord, 'Word2007');
        $objWriter->save('php://output');
    }

    /**
     * 生成合同
     * */
    public function test()
    {

        // 1. 设置自定义的临时目录
        Settings::setTempDir('D:\\www\\blind\\temp');

        // 2. 加载指定的模板文件
        $templateFilePath = 'D:\\www\\blind\\public\\contract.docx'; // 模板路径
        $templateProcessor = new TemplateProcessor($templateFilePath);

        // 3. 动态替换合同内容
        $templateProcessor->setValue('name', '张三');                // 动态设置姓名
        $templateProcessor->setValue('phone', '13812345678');        // 动态设置手机号

        // 4. 保存生成的文档
        $outputFilePath = 'D:\\www\\blind\\temp\\generated_contract.docx';
        $templateProcessor->saveAs($outputFilePath);

        echo "合同生成成功，文件已保存至：{$outputFilePath}";
    }

    public function upload(Request $request)
    {
        // 获取请求体内容
        $input = $request->getContent();

        // 将 JSON 数据解析为数组
        $data = json_decode($input, true);

        // 检查 JSON 解析错误
        if (json_last_error() !== JSON_ERROR_NONE) {
            return json(['status' => 'error', 'message' => 'JSON解析错误: ' . json_last_error_msg()]);
        }

        // 处理上传的PDF数据
        if (isset($data['pdf'])) {
            $pdfData = $data['pdf'];

            // 生成文件名
            $fileName = 'contract_' . time() . '.pdf'; // 以 PDF 格式保存
            $filePath = './uploads/' . $fileName;

            // 将 Base64 数据写入文件
            if (file_put_contents($filePath, base64_decode($pdfData)) !== false) {
                return json(['status' => 'success', 'message' => '文件上传成功']);
            } else {
                return json(['status' => 'error', 'message' => '文件写入失败']);
            }
        } else {
            return json(['status' => 'error', 'message' => '没有上传数据']);
        }
    }

    public function getAppletVersion()
    {
        $applet_version = C('APPLET_VERSION');
        $version_msg = C('APPLET_VERSION_MSG');

        apiReturn(1, $version_msg, $applet_version);
    }

    public function getAppletVersion2()
    {
        $applet_version = C('APPLET_VERSION');
        $version_msg = C('APPLET_VERSION_MSG');

        apiReturn(1, $version_msg, 1);
    }

    /**
     * 生成省市联动数据文件
     * */
    public function createRegionFile()
    {
        $region_list = Db::name('province')->field('province_id id,name')->order('province_id asc')->select();
        if ($region_list) {
            foreach ($region_list as &$v) {
                // 将名称当中的省和市替换为空
                $v['name'] = str_replace(['省', '市'], '', $v['name']);

                $city_list = Db::name('city')->field('city_id id,name,province_id pid')->where(['province_id' => $v['id']])->order('city_id asc')->select();
                if ($city_list) {
                    foreach ($city_list as &$val) {
                        $val['name'] = str_replace(['省', '市'], '', $val['name']);
                    }
                }
                $v['city_list'] = $city_list ? : [];
            }
        }

        file_put_contents(RUNTIME_PATH . 'region.json', json_encode($region_list, JSON_UNESCAPED_UNICODE));
    }

    /**
     * 获取顶部图片
     * */
    public function getTopImg()
    {
        return apiReturn(1, '获取数据成功', getHost() . '/static/xcx/top-20250212.png');
    }

    /**
     * 获取底部菜单
     * */
    public function getTabbar()
    {
        $list = Db::name('tabbar')->field('path,name text,img iconPath,active_img selectedIconPath')->order('sort asc, id asc')->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['iconPath'] = getPicture($v['iconPath']);
                $v['selectedIconPath'] = getPicture($v['selectedIconPath']);
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '获取数据失败');
        }
    }

    /**
     * 获取openid
     */
    public function getOpenid()
    {
        $input = Request()->param();

        $code = $input['code'];

        if (empty($code)) apiReturn(2, '系统繁忙，请稍后再试~');

        $appid = C('XCX_APPID');
        $secret = C('XCX_SECRET');
        $grant_type = 'authorization_code';
        $url = 'https://api.weixin.qq.com/sns/jscode2session?';

        $param = [
            'appid' => $appid,
            'secret' => $secret,
            'js_code' => $code,
            'grant_type' => $grant_type
        ];
        $param_str = http_build_query($param);
        $url .= $param_str;
        $json_res = httpsRequest($url);
        $user_data = json_decode($json_res);

        if ($openid = $user_data->openid) {
            apiReturn(1, '获取数据成功', $openid);
        } else {
            apiReturn(2, '系统繁忙，请稍后再试~');
        }
    }


    /**
     * 获取手机号
     * */
    public function getMobile()
    {
        $input = Request()->param();

        $code = $input['code'];

        if (empty($code) || $code == 'undefined') apiReturn(2, 'code缺失');

        $token = get_access_token('xcx_access_token.json', 2);
        if (empty($token)) apiReturn(2, 'TOKEN缺失');

        $url = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=' . $token . '&code=' . $code;

        $data = [
            'code' => $code
        ];
        $result = httpsRequest($url, json_encode($data));
        $result = json_decode($result, true);

        if ($result['errcode'] == 0) {
            $mobile = $result['phone_info']['phoneNumber'];

            if ($mobile) {
                apiReturn(1, '获取数据成功', $mobile);
            } else {
                apiReturn(2, '系统繁忙，请稍后再试');
            }
        } else {
            if ($result['errcode'] == 40001) {
                apiReturn(2, '系统繁忙，请重新获取手机号');
            } elseif ($result['errcode'] == 40029) {
                apiReturn(3, '获取手机号失败，请前往【我 => 设置 => 关于微信】将微信版本更新至不低于8.0.16后，再回到此界面点击绑定手机');
            } else {
                apiReturn(2, '系统繁忙，请稍后再试~');
            }
        }
    }

    /**
     * 获取用户信息
     * */
    public function userCenter()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $scene_user_id = $input['scene_user_id'] ? : 0;

        if (empty($user_id)) apiReturn(3, '您还未登录，请先登录');

        $info = Db::name('user')->field('id,avatar,id_num,role_id,qr,profit,up_user_id,show_step')->where(['id' => $user_id])->find();
        if ($info) {
            if ($info['status'] == 2) apiReturn(2, '您的账号已被禁用，请联系管理员');


            // 查看该用户已开通的最高等级会员
            $user_service_info = Db::name('user_service')->where(['user_id' => $user_id, 'expire_time' => ['gt', time()]])->order('price desc, id desc')->find();
            if ($service_id = $user_service_info['service_id']) $level_num = Db::name('service')->where('id', $service_id)->value('level_num');

            $info['level_num'] = $level_num ? : 0;
            $info['avatar'] = doAvatar($info['avatar']);
            $info['nickname'] = getRealName($user_id);

            $details_info = Db::name('user_details')->field('username,rz_status')->where(['user_id' => $user_id])->find();
            $info['rz_status'] = $details_info['rz_status'] ? : 0;
            $username = $details_info['username'] ? : $info['nickname'];
            $info['username'] = mb_substr($username, 0, 4, 'UTF-8');

            // 用户角色
            $role_name = '普通用户';
            if ($role_id = $info['role_id']) {
                $role_info = Db::name('role')->where(['id' => $role_id])->find();
                $role_name = $role_info['name'];
                $role_content = doEditorContent($role_info['content']);
            }
            $info['role_name'] = $role_name;
            $info['role_content'] = $role_content;

            // 关注我的数量
            $info['follow_me_count'] = Db::name('follow')->where(['follow_user_id' => $user_id, 'is_follow' => 1])->count();
            // 我关注的数量
            $info['me_follow_count'] = Db::name('follow')->where(['user_id' => $user_id, 'is_follow' => 1])->count();

            $qr = $info['qr'];
            if (!$qr) $qr = createUserQr($user_id, 2);
            $info['qr_path'] = getPicture($qr);

            $info['qr_path'] = $info['qr'] ? getPicture($info['qr']) : '';
            // 总推广人数
            $share_count = Db::name('user')->where(['up_user_id' => $user_id, 'status' => 1])->count();
            $info['share_count'] = $share_count;

            $withdraw_type = C('WITHDRAW_TYPE');
            $info['withdraw_type'] = $withdraw_type;

            $up_info = Db::name('user')->where(['id' => $scene_user_id])->find();
            // 绑定上下级关系
            if ($user_id != $scene_user_id && $scene_user_id > 0 && $info['up_user_id'] == 0 && $up_info['role_id'] > 1) {
                $res = Db::name('user')->where(['id' => $user_id])->setField('up_user_id', $scene_user_id);
                if ($res) $info['up_user_id'] = $scene_user_id;
            }

            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '用户数据不存在');
        }
    }

    public function bindUser()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $scene_user_id = $input['scene_user_id'];

        if (empty($user_id) || empty($scene_user_id)) apiReturn(2, '参数错误');

        $info = Db::name('user')->where(['id' => $user_id])->find();
        if (empty($info)) apiReturn(2, '用户数据不存在');

        $up_info = Db::name('user')->where(['id' => $scene_user_id])->find();
        if (empty($up_info)) apiReturn(2, '上级用户数据不存在');

        if ($up_info['role_id'] <= 1) apiReturn(2, '普通用户不可绑定');

        if ($user_id != $scene_user_id && $scene_user_id > 0 && $info['up_user_id'] == 0) {
            $share_user_info = Db::name('user')->where(['id' => $scene_user_id])->find();
            if (empty($info)) apiReturn(2, '分享人用户数据不存在');

            if ($share_user_info['up_user_id'] == $user_id) apiReturn(2, '两个用户之间不可相互绑定');

            $res = Db::name('user')->where(['id' => $user_id])->setField('up_user_id', $scene_user_id);
            if ($res) {
                apiReturn(1, '绑定成功');
            } else {
                apiReturn(2, '绑定失败');
            }
        }
    }

    public function openidToUserid()
    {
        $input = Request()->param();

        $code = $input['code'];

        if (empty($code)) apiReturn(2, '系统繁忙，请稍后再试~');

        $appid = C('XCX_APPID');
        $secret = C('XCX_SECRET');
        $grant_type = 'authorization_code';
        $url = 'https://api.weixin.qq.com/sns/jscode2session?';

        $param = [
            'appid' => $appid,
            'secret' => $secret,
            'js_code' => $code,
            'grant_type' => $grant_type
        ];
        $param_str = http_build_query($param);
        $url .= $param_str;

        $user_data = json_decode(httpsRequest($url));

        if ($user_data->errcode) apiReturn(2, '系统繁忙，请稍后再试~');

        $openid = $user_data->openid;

        if (empty($openid)) apiReturn(2, '登录失败');

        $user_id = Db::name('user')->where(['openid' => $openid])->value('id');

        if ($user_id) {
            apiReturn(1, '登录成功', $user_id);
        } else {
            apiReturn(2, '新用户，走注册流程');
        }
    }

    /**
     * 登录
     * */
    public function login()
    {
        $input = Request()->param();

        $openid = $input['openid'];
        $avatar = $input['avatar'];
        $nickname = $input['nickname'];
        $mobile = $input['mobile'];

        if (empty($openid)) apiReturn(2, 'openid缺失');
        if (empty($avatar)) apiReturn(2, '请上传头像信息');
        if (empty($nickname)) apiReturn(2, '请填写昵称');
        if (empty($mobile)) apiReturn(2, '请获取手机号');

        $mobile_count = Db::name('user')->where(['mobile' => $mobile])->count();
        if ($mobile_count > 0) apiReturn(2, '该手机号已使用');

        Db::startTrans();
        try {
            $count = Db::name('user')->where(['openid' => $openid])->count();
            if ($count) {
                $user_id = Db::name('user')->where(['openid' => $openid])->value('id');
            } else {
                $data = [
                    'openid' => $openid,
                    'avatar' => $avatar,
                    'nickname' => $nickname,
                    'mobile' => $mobile,
                    'id_num' => createIdNum(),
                    'create_time' => time()
                ];

                $user_id = Db::name('user')->insertGetId($data);
                if ($user_id) {
                    createUserQr($user_id, 2);

                    $user_details_data = [
                        'user_id' => $user_id,
                        'create_time' => time()
                    ];
                    Db::name('user_details')->insert($user_details_data);
                }
            }

            Db::commit();
            apiReturn(1, '登录成功', $user_id);
        } catch (\Exception $e) {
            Db::rollback();
            apiReturn(2, '系统繁忙，请稍后再试~');
        }
    }

    /**
     * 1：相册、联系方式无权限查看提示，2：购买服务成功提示
     * */
    public function getAuthArticle()
    {
        $input = Request()->param();

        $type = $input['type'] ? : 1;

        $content = Db::name('auth_article')->where(['type' => $type])->value('content');
        $content = doEditorContent($content);
        apiReturn(1, '获取数据成功', $content);
    }

    /**
     * 用户资料
     * */
    public function userInfo()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $follow_user_id = $input['follow_user_id'] ? : 0;// 被查看人的用户id

        if (empty($user_id) && empty($follow_user_id)) apiReturn(2, '用户ID缺失');

        // 查看该用户已开通的最高等级会员
        $user_service_info = Db::name('user_service')->where(['user_id' => $user_id, 'expire_time' => ['gt', time()]])->order('price desc, id desc')->find();

        $level_num = Db::name('service')->where('id', $user_service_info['service_id'])->value('level_num');

        $up_user_id = 0;
        /*if ($follow_user_id > 0) {
            // 查看被查看人是否是自己的下级，是的话，就不消耗查看次数
            $up_user_id = Db::name('user')->where(['id' => $follow_user_id])->value('up_user_id');
            if ($up_user_id != $user_id) {
                if (empty($user_service_info)) {
                    // 未开通服务可以查看3次用户资料

                    $is_look = Db::name('user_look')->where(['user_id' => $user_id, 'to_user_id' => $follow_user_id, 'is_valid' => 1, 'is_free' => 1])->count();
                    if ($is_look == 0) {
                        // 已经免费查看的次数
                        $free_look_count = Db::name('user_look')->where(['user_id' => $user_id, 'is_valid' => 1, 'is_free' => 1])->count();
                        if ($free_look_count >= 3) {
                            apiReturn(3, '3次查看主页机会已用完');
                        } else {
                            $is_free = 1;
                        }
                    }
                } else {
                    $level_num = Db::name('service')->where('id', $user_service_info['service_id'])->value('level_num');

                    $is_look = Db::name('user_look')->where(['user_id' => $user_id, 'to_user_id' => $follow_user_id, 'is_valid' => 1, 'is_free' => 0])->count();
                    if ($is_look == 0) {
                        // 查看今天已经查看了几个用户的信息
                        $today_start = strtotime(date('Y-m-d'));
                        $today_end = strtotime(date('Y-m-d 23:59:59'));
                        $look_count = Db::name('user_look')->where(['user_id' => $user_id, 'is_free' => 0, 'create_time' => ['between', [$today_start, $today_end]]])->count();
                        if ($look_count >= $user_service_info['look_count']) apiReturn(3, '您今日查看用户资料已达上限');
                    }
                }
            }
        }*/


        $where_user_id = $follow_user_id ? : $user_id;

        $info = Db::name('user u')->join('user_details d', 'u.id = d.user_id', 'left')
            ->field('u.avatar,u.nickname,u.id_num,u.status,u.wechat,u.qq,u.mobile,d.*')
            ->where(['u.id' => $where_user_id])
            ->find();

        if ($info) {
            if ($info['status'] == 2) apiReturn(2, '您的账号已被禁用，请联系管理员');

            // 记录用户之间的查看记录
            /*if ($is_look == 0 && $follow_user_id > 0 && $up_user_id != $user_id) {
                $user_look_data = [
                    'user_id' => $user_id,
                    'to_user_id' => $follow_user_id,
                    'is_valid' => 1,
                    'is_free' => $is_free ? 1 : 0,
                    'create_time' => time()
                ];
                Db::name('user_look')->insert($user_look_data);
            }*/

            $info['requirement_marital_status_arr'] = $info['requirement_marital_status'] ? explode(',', $info['requirement_marital_status']) : [];

            $info['residence'] = $info['residence'] ? : '';
            $info['age'] = $info['age'] ? : '';

            if ($info['status'] == 2) apiReturn(2, '您的账号已被禁用，请联系管理员');

            $info['avatar_path'] = doAvatar($info['avatar']);
            $info['photos_arr'] = array_slice(doImgs($info['photos']), 0, 4);
            $info['birth_year'] = $info['birth_date'] ? explode('-', $info['birth_date'])[0] . '年' : '';

            // 关注我的数量
            $info['follow_me_count'] = Db::name('follow')->where(['follow_user_id' => $where_user_id, 'is_follow' => 1])->count();
            // 我关注的数量
            $info['me_follow_count'] = Db::name('follow')->where(['user_id' => $where_user_id, 'is_follow' => 1])->count();

            // 职业下拉框数据
            $occupationData = array_values(array_filter(C('OCCUPATION')));
            $info['occupationData'] = $occupationData;
            // 体型下拉框数据
            $bodyTypeData = array_values(array_filter(C('BODY_TYPE')));
            $info['bodyTypeData'] = $bodyTypeData;
            // 婚况下拉框数据
            $maritalStatusData = array_values(array_filter(C('MARITAL_STATUS')));
            $info['maritalStatusData'] = $maritalStatusData;
            // 学历下拉框数据
            $educationLevelData = array_values(array_filter(C('EDUCATION_LEVEL')));
            $info['educationLevelData'] = $educationLevelData;
            // 公司下拉框数据
            $companyTypeData = array_values(array_filter(C('COMPANY_TYPE')));
            $info['companyTypeData'] = $companyTypeData;
            // 年收入下拉框数据
            $annualIncomeData = array_values(array_filter(C('ANNUAL_INCOME')));
            $info['annualIncomeData'] = $annualIncomeData;
            // 住房下拉框数据
            $housingStatusData = array_values(array_filter(C('HOUSING_STATUS')));
            $info['housingStatusData'] = $housingStatusData;
            // 车辆框数据
            $carStatusData = array_values(array_filter(C('CAR_STATUS')));
            $info['carStatusData'] = $carStatusData;
            // 小孩数据
            $hasChildrenData = array_values(array_filter(C('HAS_CHILDREN')));
            $info['hasChildrenData'] = $hasChildrenData;
            // 民族数据
            $ethnicityData = array_values(array_filter(C('ETHNICITY')));
            $info['ethnicityData'] = $ethnicityData;
            // 抽烟数据
            $smokingData = array_values(array_filter(C('SMOKING')));
            $info['smokingData'] = $smokingData;
            // 喝酒数据
            $drinkingData = array_values(array_filter(C('DRINKING')));
            $info['drinkingData'] = $drinkingData;

            if ($follow_user_id > 0 && $user_id > 0 && $user_id != $follow_user_id) {
                $is_follow = Db::name('follow')->where(['user_id' => $user_id, 'follow_user_id' => $follow_user_id])->value('is_follow');
                $info['is_follow'] = $is_follow ? 1 : 0;
            } else {
                $info['is_follow'] = -1;
            }

            $auto_content = Db::name('auth_article')->where(['type' => 1])->value('content');
            $auto_content = doEditorContent($auto_content);
            $info['auto_content'] = $auto_content;

            $info['nickname'] = getRealName($where_user_id);

            $can_chat = $user_service_info['service_id'] > 0 ? getCanChat($user_id, $follow_user_id, $user_service_info['service_id']) : false;
            $info['can_chat'] = (int)$can_chat;

            $info['level_num'] = $level_num ? : 0;

            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '用户数据不存在');
        }
    }


    /**
     * 修改用户头像
     * */
    public function saveUserAvatar()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $avatar = $input['avatar'];

        if (empty($user_id)) apiReturn(3, '您还未登录，请先登录');
        if (empty($avatar)) apiReturn(2, '请上传头像');

        $res = Db::name('user')->where(['id' => $user_id])->setField('avatar', $avatar);
        if ($res) {
            apiReturn(1, '修改头像成功');
        } else {
            apiReturn(2, '修改头像失败');
        }

    }

    public function skip()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];

        if (empty($user_id)) apiReturn(3, '您还未登录，请先登录');

        $res = Db::name('user')->where(['id' => $user_id])->setField('show_step', 0);
        if ($res) {
            apiReturn(1, '成功');
        } else {
            apiReturn(2, '失败');
        }
    }

    public function saveUserDetailsStep()
    {
        $formData = Request()->param();

        $user_id = $formData['user_id'];
        $step = $formData['step'] ? : 1;

        if (empty($user_id)) apiReturn(3, '您还未登录，请先登录');

        switch ($step) {
            case 1:
                if ($formData['birth_date']) {
                    if (time() < strtotime($formData['birth_date'])) apiReturn(2, '年份不能大于当前时间');
                    $age = calculateAge($formData['birth_date']);
                } else {
                    $age = 0;
                }

                $data = [
                    'username' => $formData['username'],
                    'gender' => $formData['gender'],
                    'birth_date' => $formData['birth_date'],
                    'age' => $age,
                ];
                break;
            case 2:
                $data = [
                    'residence' => $formData['residence'],
                    'height' => $formData['height'],
                    'weight' => $formData['weight']
                ];
                break;
            case 3:
                $data = [
                    'marital_status' => $formData['marital_status'],
                    'annual_income' => $formData['annual_income'],
                    'housing_status' => $formData['housing_status'],
                    'car_status' => $formData['car_status']
                ];
                break;
            case 4:
                $data = [
                    'requirement_age' => $formData['requirement_age'],
                    'requirement_height' => $formData['requirement_height'],
                    'requirement_marital_status' => $formData['requirement_marital_status'],
                    'requirement_buying_status' => $formData['requirement_buying_status'] ? : '不限',
                    'requirement_car_status' => $formData['requirement_car_status'] ? : '不限',
                    'requirement_has_children' => $formData['requirement_has_children'] && $formData['requirement_has_children'] != 'undefined' ? $formData['requirement_has_children'] : '不限'
                ];
                break;
        }

        $data['update_time'] = time();

        $res = Db::name('user_details')->where(['user_id' => $user_id])->update($data);
        if ($res) {
            Db::name('user')->where(['id' => $user_id])->setField('show_step', 0);
            apiReturn(1, '保存成功');
        } else {
            apiReturn(2, '保存失败');
        }
    }

    /**
     * 保存用户资料
     * */
    public function saveUserDetails()
    {
        $formData = Request()->param();

        $user_id = $formData['user_id'];
        $type = $formData['type'] ? : 1;

        if (empty($user_id)) apiReturn(3, '您还未登录，请先登录');
        switch ($type) {
            case 1:
                if (empty($formData['username'])) apiReturn(2, '请输入姓名');
                if (empty($formData['gender'])) apiReturn(2, '请选择性别');
                if (empty($formData['birth_date'])) apiReturn(2, '请选择年份');
                if ($formData['birth_date']) {
                    if (time() < strtotime($formData['birth_date'])) apiReturn(2, '年份不能大于当前时间');
                    $age = calculateAge($formData['birth_date']);
                } else {
                    $age = 0;
                }
                if (empty($formData['residence'])) apiReturn(2, '请选择居住地');
                if (empty($formData['height'])) apiReturn(2, '请选择身高');
                if (empty($formData['weight'])) apiReturn(2, '请选择体重');
                if (empty($formData['occupation'])) apiReturn(2, '请选择职业');
                if (empty($formData['marital_status'])) apiReturn(2, '请选择婚况');
                if (empty($formData['annual_income'])) apiReturn(2, '请选择年收入');
                if (empty($formData['housing_status'])) apiReturn(2, '请选择住房');

                if (empty($formData['requirement_age'])) apiReturn(2, '请选择择偶年龄要求');
                if (empty($formData['requirement_height'])) apiReturn(2, '请选择择偶身高要求');
                if (empty($formData['requirement_residence'])) apiReturn(2, '请选择择偶居住地要求');

                $data = [
                    'username' => $formData['username'],
                    'gender' => $formData['gender'],
                    'birth_date' => $formData['birth_date'],
                    'age' => $age,
                    'residence' => $formData['residence'],
                    'hukou' => $formData['hukou'],
                    'height' => $formData['height'],
                    'weight' => $formData['weight'],
                    'occupation' => $formData['occupation'],
                    'body_type' => $formData['body_type'],
                    'marital_status' => $formData['marital_status'],
                    'education_level' => $formData['education_level'],
                    'company_type' => $formData['company_type'],
                    'annual_income' => $formData['annual_income'],
                    'ethnicity' => $formData['ethnicity'],
                    'smoking' => $formData['smoking'],
                    'drinking' => $formData['drinking'],
                    'has_children' => $formData['has_children'],
                    'housing_status' => $formData['housing_status'],
                    'car_status' => $formData['car_status'],
                    'requirement_age' => $formData['requirement_age'],
                    'requirement_height' => $formData['requirement_height'],
                    'requirement_body_type' => $formData['requirement_body_type'] ? : '不限',
                    'requirement_marital_status' => $formData['requirement_marital_status'],
                    'requirement_education_level' => $formData['requirement_education_level'] ? : '不限',
                    'requirement_annual_income' => $formData['requirement_annual_income'] ? : '不限',
                    'requirement_residence' => $formData['requirement_residence'],
                    'requirement_has_children' => $formData['requirement_has_children'] && $formData['requirement_has_children'] != 'undefined' ? $formData['requirement_has_children'] : '不限',
                    'requirement_ethnicity' => $formData['requirement_ethnicity'] ? : '不限',
                    'requirement_smoking' => $formData['requirement_smoking'] ? : '不限',
                    'requirement_drinking' => $formData['requirement_drinking'] ? : '不限',
                    'requirement_buying_status' => $formData['requirement_buying_status'] ? : '不限',
                    'requirement_car_status' => $formData['requirement_car_status'] ? : '不限',
                    'update_time' => time()
                ];
                break;
            case 2:
                $data = [
                    'wechat' => $formData['wechat'],
                    'qq' => $formData['qq'],
                    'mobile' => $formData['mobile'],
                    'update_time' => time()
                ];
        }

        $res = Db::name('user_details')->where(['user_id' => $user_id])->update($data);
        if ($res) {
            apiReturn(1, '保存成功');
        } else {
            apiReturn(2, '保存失败');
        }
    }

    /**
     * 保存用户资料【联系方式】
     * */
    public function saveUserContact()
    {
        $formData = Request()->param();

        $user_id = $formData['user_id'];

        if (empty($user_id)) apiReturn(3, '您还未登录，请先登录');

        $user_info = Db::name('user')->field('id,mobile')->where('id', $user_id)->find();
        if (empty($user_info)) apiReturn(3, '用户信息不存在');

        if ($user_info['mobile'] && $formData['mobile'] != $user_info['mobile']) apiReturn(2, '手机号不能被修改');

        $data = [
            'wechat' => $formData['wechat'],
            'qq' => $formData['qq'],
            'update_time' => time()
        ];
        if (!$user_info['mobile']) $data['mobile'] = $formData['mobile'];

        $res = Db::name('user')->where(['id' => $user_id])->update($data);
        if ($res) {
            apiReturn(1, '保存成功');
        } else {
            apiReturn(2, '保存失败');
        }
    }

    /**
     * 保存用户资料【相册】
     * */
    public function saveUserPhotos()
    {
        $formData = Request()->param();

        $user_id = $formData['user_id'];
        $photos_id = $formData['photos_id'];

        if (empty($user_id)) apiReturn(3, '您还未登录，请先登录');
        if (empty($photos_id)) apiReturn(2, '请上传照片');

        $data = [
            'photos' => $photos_id,
            'update_time' => time()
        ];

        $res = Db::name('user_details')->where(['user_id' => $user_id])->update($data);
        if ($res) {
            apiReturn(1, '保存成功');
        } else {
            apiReturn(2, '保存失败');
        }
    }

    /**
     * 关注/取消关注
     * */
    public function follow()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];// 当前登录用户id
        $follow_user_id = $input['follow_user_id'];

        if (empty($user_id)) apiReturn(3, '您还未登录，请先登录');

        $time = time();
        $info = Db::name('follow')->where(['user_id' => $user_id, 'follow_user_id' => $follow_user_id])->find();
        if (empty($info)) {
            // 第一次关注
            $data = [
                'user_id' => $user_id,
                'follow_user_id' => $follow_user_id,
                'is_follow' => 1,
                'update_time' => $time,
                'create_time' => $time
            ];
            $res = Db::name('follow')->insert($data);
            if ($res) {
                apiReturn(1, '关注成功');
            } else {
                apiReturn(2, '关注失败');
            }
        } else {
            // 之前已经关注或者取消关注
            $is_follow = $info['is_follow'] == 1 ? 0 : 1;
            $data = [
                'is_follow' => $is_follow,
                'update_time' => $time
            ];
            $res = Db::name('follow')->where(['id' => $info['id']])->update($data);
            if ($res) {
                apiReturn(1, $is_follow == 1 ? '关注成功' : '取消关注成功');
            } else {
                apiReturn(2, $is_follow == 1 ? '关注失败' : '取消关注失败');
            }
        }
    }


    /**
     * 关注列表
     * */
    public function followList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $type = $input['type'] ? : 1;// 1:我关注的 2:关注我的
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        if (empty($user_id)) apiReturn(3, '您还未登录，请先登录');

        $field = 'f.id,f.user_id,f.follow_user_id,d.username,d.gender,d.residence,d.age,d.height,d.marital_status,d.annual_income,d.hobby,d.requirement_marital_status,d.requirement_age,d.requirement_height,d.requirement_annual_income';
        if ($type == 1) {
            $list = Db::name('follow f')->join('blind_user_details d', 'f.follow_user_id = d.user_id')
                ->field($field)
                ->where(['f.user_id' => $user_id, 'f.is_follow' => 1])
                ->page($page, $pagesize)
                ->select();
        } else {
            $list = Db::name('follow f')->join('blind_user_details d', 'f.user_id = d.user_id')
                ->field($field)
                ->where(['f.follow_user_id' => $user_id, 'f.is_follow' => 1])
                ->page($page, $pagesize)
                ->select();
        }

        if ($list) {
            foreach ($list as &$v) {
                $avatar = Db::name('user')->where(['id' => $type == 1 ? $v['follow_user_id'] : $v['user_id']])->value('avatar');;
                $v['avatar'] = doAvatar($avatar);
                $v['hobby'] = $v['hobby'] && $v['hobby'] != 'null' ? json_decode($v['hobby'], true) : [];
                $v['hobby_str'] = implode('、', $v['hobby']);
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }

    /**
     * 取消关注
     * */
    public function cancelFollow()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $follow_user_id = $input['follow_user_id'];

        if (empty($user_id)) apiReturn(3, '您还未登录，请先登录');

        $res = Db::name('follow')->where(['user_id' => $user_id, 'follow_user_id' => $follow_user_id])->update(['is_follow' => 0, 'update_time' => time()]);
        if ($res) {
            apiReturn(1, '取消关注成功');
        } else {
            apiReturn(2, '取消关注失败');
        }
    }

    /**
     * 推广列表
     * */
    public function shareUserList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        if (empty($user_id)) apiReturn(3, '您还未登录，请先登录');

        $list = Db::name('user')->field('id,nickname,id_num,mobile,avatar,create_time')->where(['up_user_id' => $user_id])->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $username = Db::name('user_details')->where(['user_id' => $v['id']])->value('username');
                $v['username'] = $username ? : $v['nickname'];
                $v['avatar'] = doAvatar($v['avatar']);
                $v['mobile'] = $v['mobile'] ? substr_replace($v['mobile'], '****', 3, 4) : '';
                $v['create_time_desc'] = timeFormat($v['create_time'], 'Y年m月d日');
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }

    /**
     * 首页banner
     * */
    public function indexBanner()
    {
        $banner_list = Db::name('banner')->field('id,img,type,to_id')->select();

        if ($banner_list) {
            foreach ($banner_list as &$v) {
                $v['img'] = getPicture($v['img']);
            }
            apiReturn(1, '获取数据成功', $banner_list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }

    /**
     * banner文章详情
     * */
    public function bannerArticleDetail()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '文章ID缺失');

        $info = Db::name('article')->field('id,title,content,create_time')->where(['id' => $id])->find();
        if ($info) {
            $info['content'] = doEditorContent($info['content']);
            $info['create_time'] = timeFormat($info['create_time']);

            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '文章不存在或已删除');
        }
    }

    /**
     * 首页推荐列表
     * */
    public function indexRecommendUserList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'] ? : 0;

        $where['d.rz_status'] = 1;
        $where['u.role_id'] = 1;// 普通用户
        $where['u.is_recommend'] = 1;
        if ($user_id) $where['u.id'] = ['neq', $user_id];

        $field = 'u.id,u.avatar,d.gender,d.birth_date,d.residence,d.age,d.height,d.marital_status,d.annual_income,d.hobby,d.requirement_marital_status,d.requirement_age,d.requirement_height,d.requirement_annual_income,d.requirement_buying_status';
        $list = Db::name('user u')->join('user_details d', 'u.id = d.user_id')
            ->field($field)
            ->where($where)
            //            ->order('u.sort asc, u.id desc')
            ->orderRaw('RAND()')
            ->limit(1)
            ->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['username'] = getRealName($v['id']);
                $v['avatar'] = doAvatar($v['avatar']);
                $v['hobby_str'] = !empty($v['hobby']) && $v['hobby'] != 'null' ? implode('、', json_decode($v['hobby'], true)) : '';
                $v['age'] = $v['age'] ? : (calculateAge($v['birth_date']) ? calculateAge($v['birth_date']) : '-');
                $v['residence'] = $v['residence'] ? : '-';

                $xm_arr = [
                    $v['requirement_marital_status'], $v['requirement_age'], $v['requirement_height'], $v['requirement_annual_income'], $v['requirement_buying_status']
                ];
                $v['xm_str'] = implode('、', array_filter($xm_arr));
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }

    /**
     * 获取用户择偶要求
     * */
    public function getUserRequirement()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];

        if (empty($user_id)) apiReturn(2, '用户ID缺失');

        $info = Db::name('user_details')->field('requirement_age,requirement_height,requirement_body_type,requirement_marital_status,requirement_education_level,requirement_annual_income,requirement_residence,requirement_has_children,requirement_buying_status,requirement_car_status')->where(['user_id' => $user_id])->find();
        if ($info) {
            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }

    public function testAge()
    {
        $list = Db::name('user_details')->field('id,birth_date')->where(['birth_date' => ['gt', 0]])->select();
        if ($list) {
            foreach ($list as &$v) {
                if ($v['birth_date'] != '0000-00-00') {
                    Db::name('user_details')->where(['id' => $v['id']])->update(['age' => calculateAge($v['birth_date'])]);
                }
            }
        }
    }

    /**
     * 获取下拉框数据
     * */
    public function getSelectData()
    {
        $info = [];
        // 职业下拉框数据
        $occupationData = array_values(array_filter(C('OCCUPATION')));
        $info['occupationData'] = $occupationData;
        // 体型下拉框数据
        $bodyTypeData = array_values(array_filter(C('BODY_TYPE')));
        $info['bodyTypeData'] = $bodyTypeData;
        // 婚况下拉框数据
        $maritalStatusData = array_values(array_filter(C('MARITAL_STATUS')));
        $info['maritalStatusData'] = $maritalStatusData;
        // 学历下拉框数据
        $educationLevelData = array_values(array_filter(C('EDUCATION_LEVEL')));
        $info['educationLevelData'] = $educationLevelData;
        // 公司下拉框数据
        $companyTypeData = array_values(array_filter(C('COMPANY_TYPE')));
        $info['companyTypeData'] = $companyTypeData;
        // 年收入下拉框数据
        $annualIncomeData = array_values(array_filter(C('ANNUAL_INCOME')));
        $info['annualIncomeData'] = $annualIncomeData;
        // 住房下拉框数据
        $housingStatusData = array_values(array_filter(C('HOUSING_STATUS')));
        $info['housingStatusData'] = $housingStatusData;
        // 车辆框数据
        $carStatusData = array_values(array_filter(C('CAR_STATUS')));
        $info['carStatusData'] = $carStatusData;
        // 小孩数据
        $hasChildrenData = array_values(array_filter(C('HAS_CHILDREN')));
        $info['hasChildrenData'] = $hasChildrenData;

        apiReturn(1, '获取数据成功', $info);
    }

    /**
     * 搜索列表
     * */
    public function searchUserList()
    {
        $input = Request()->param();

        $tab = $input['tab'] ? : 1;// 1：推荐，2：匹配我的
        $user_id = $input['user_id'] ? : 0;
        $is_search = $input['is_search'] ? : 0; // 是否是搜索，只有tab==1是才生效；1：是，0：否
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        $where['d.rz_status'] = 1;
        $where['u.role_id'] = 1;// 普通用户
        if ($user_id) $where['u.id'] = ['neq', $user_id];

        $sort = '';
        if ($tab == 1) {
            // 推荐列表；推荐不作为条件，当切换到推荐列表的时候，推荐的排序靠前
            $sort = 'u.is_recommend asc ';

            if ($is_search) {
                // 加入搜索条件
                $idOrName = $input['idOrName'] ? : '';
                $gender = $input['gender'] ? : '';
                $age = $input['age'] ? : '';
                $height = $input['height'] ? : '';
                $weight = $input['weight'] ? : '';
                $residence = $input['residence'] ? : '';
                $hukou = $input['hukou'] ? : '';
                $marital_status = $input['marital_status'] ? : '';
                $education_level = $input['education_level'] ? : '';
                $occupation = $input['occupation'] ? : '';
                $annual_income = $input['annual_income'] ? : '';
                $housing_status = $input['housing_status'] ? : '';
                $car_status = $input['car_status'] ? : '';
                $has_children = $input['has_children'] ? : '';

                if ($idOrName) $where['u.id_num|d.username'] = ['like', '%' . $idOrName . '%'];
                if ($gender) $where['d.gender'] = $gender;
                // 年龄范围
                if ($age) {
                    $age = explode('-', str_replace('岁', '', $age));
                    $where['d.age'] = ['between', [$age[0], $age[1]]];
                }
                // 身高范围
                if ($height) {
                    $height = explode('-', str_replace('cm', '', $height));
                    $where['d.height'] = ['between', [$height[0], $height[1]]];
                }
                // 体重范围
                if ($weight) {
                    $weight = explode('-', str_replace('kg', '', $weight));
                    $where['d.weight'] = ['between', [$weight[0], $weight[1]]];
                }
                if ($residence) $where['d.residence'] = ['like', "$residence%"];
                if ($hukou) $where['d.hukou'] = ['like', "$hukou%"];
                if ($marital_status) $where['d.marital_status'] = $marital_status;
                if ($education_level) $where['d.education_level'] = $education_level;
                if ($occupation) $where['d.occupation'] = $occupation;
                if ($annual_income) $where['d.annual_income'] = $annual_income;
                if ($housing_status) $where['d.housing_status'] = $housing_status;
                if ($car_status) $where['d.car_status'] = $car_status;
                if ($has_children) $where['d.has_children'] = $has_children;
            }
            /*else {
                $where['u.is_recommend'] = 1;
            }*/
        } else {
            // 加入择偶要求条件
            $requirement_age = $input['requirement_age'] ? : '';
            $requirement_height = $input['requirement_height'] ? : '';
            $requirement_body_type = $input['requirement_body_type'] ? : '';
            $requirement_marital_status = $input['requirement_marital_status'] ? : '';
            $requirement_education_level = $input['requirement_education_level'] ? : '';
            $requirement_annual_income = $input['requirement_annual_income'] ? : '';
            $requirement_residence = $input['requirement_residence'] ? : '';
            $requirement_ethnicity = $input['requirement_ethnicity'] ? : '';
            $requirement_smoking = $input['requirement_smoking'] ? : '';
            $requirement_drinking = $input['requirement_drinking'] ? : '';
            $requirement_has_children = $input['requirement_has_children'] ? : '';
            $requirement_buying_status = $input['requirement_buying_status'] ? : '';
            $requirement_car_status = $input['requirement_car_status'] ? : '';

            // 年龄
            if ($requirement_age) {
                $age = explode('-', str_replace('岁', '', $requirement_age));
                $where['d.age'] = ['between', [$age[0], $age[1]]];
            }
            // 身高
            if ($requirement_height) {
                $height = explode('-', str_replace('cm', '', $requirement_height));
                $where['d.height'] = ['between', [$height[0], $height[1]]];
            }
            // 体型
            if ($requirement_body_type && $requirement_body_type != '不限') $where['d.body_type'] = $requirement_body_type;
            // 婚姻状况
            if ($requirement_marital_status) $where['d.marital_status'] = ['IN', explode(',', $requirement_marital_status)];
            // 学历
            if ($requirement_education_level && $requirement_education_level != '不限') $where['d.education_level'] = $requirement_education_level;
            // 年收入
            if ($requirement_annual_income && $requirement_annual_income != '不限') {
                $annual_income = explode('-', str_replace('万', '', $requirement_annual_income));
                $where['d.annual_income'] = ['between', [$annual_income[0], $annual_income[1]]];
            }
            // 居住地
            if ($requirement_residence) $where['d.residence'] = $requirement_residence;
            // 民族
            if ($requirement_ethnicity && $requirement_ethnicity != '不限') $where['d.ethnicity'] = $requirement_ethnicity;
            // 抽烟
            if ($requirement_smoking && $requirement_smoking != '不限') $where['d.smoking'] = $requirement_smoking;
            // 喝酒
            if ($requirement_drinking && $requirement_drinking != '不限') $where['d.drinking'] = $requirement_drinking;
            // 有无子女
            if ($requirement_has_children && $requirement_has_children != '不限') $where['d.has_children'] = $requirement_has_children;
            // 购房情况
            if ($requirement_buying_status && $requirement_buying_status != '不限') $where['d.housing_status'] = $requirement_buying_status;
            // 购车情况
            if ($requirement_car_status && $requirement_car_status != '不限') $where['d.car_status'] = $requirement_car_status;
        }

        if ($user_id) $user_look_ids = Db::name('user_look')->where(['user_id' => $user_id, 'is_valid' => 1])->order('create_time desc')->column('to_user_id');

        $field = 'u.id,u.avatar,d.username,d.gender,d.birth_date,d.residence,d.age,d.height,d.marital_status,d.annual_income,d.hobby,d.requirement_marital_status,d.requirement_age,d.requirement_height,d.requirement_annual_income,d.requirement_buying_status';
        $order = [];

        if (!empty($user_look_ids)) {
            $caseWhenOrder = 'CASE';
            foreach ($user_look_ids as $index => $id) {
                // 给每个 ID 分配一个排序权重
                $caseWhenOrder .= " WHEN u.id = $id THEN $index";
            }
            // 完成 CASE WHEN 语句
            $caseWhenOrder .= " ELSE " . (count($user_look_ids)) . " END";

            // 将 CASE WHEN 排序放入到最终的排序中
            $order[] = "$caseWhenOrder ASC";  // 按照指定的顺序升序排列
        }

        // 添加默认排序条件（将其放在 CASE WHEN 排序之后）
        $order[] = 'u.openid DESC, u.sort ASC, u.id DESC';

        // 将排序条件拼接为 SQL 字符串
        $list = Db::name('user u')
            ->join('user_details d', 'u.id = d.user_id')
            ->field($field)
            ->where($where)
            ->orderRaw(implode(', ', $order))  // 使用拼接后的排序字符串
            ->page($page, $pagesize)
            ->select();

        if ($list) {
            foreach ($list as &$v) {
                $v['username'] = getRealName($v['id']);
                $v['avatar'] = doAvatar($v['avatar']);
                $v['hobby'] = $v['hobby'] && $v['hobby'] != 'null' ? json_decode($v['hobby'], true) : [];
                $v['hobby_str'] = implode('、', $v['hobby']);
                $v['age'] = $v['age'] ? : (calculateAge($v['birth_date']) ? calculateAge($v['birth_date']) : '-');
                $v['residence'] = $v['residence'] ? : '-';

                $xm_arr = [
                    $v['requirement_marital_status'], $v['requirement_age'], $v['requirement_height'], $v['requirement_annual_income'], $v['requirement_buying_status']
                ];
                $v['xm_str'] = implode('、', array_filter($xm_arr));
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            if ($page == 1) {
                $gender = Db::name('user_details')->where(['user_id' => $user_id])->value('gender');
                $gender = $gender == '女' ? '男' : '女';
                // 猜你喜欢
                $list = Db::name('user u')
                    ->join('user_details d', 'u.id = d.user_id')
                    ->field($field)
                    ->where(['d.gender' => $gender, 'd.rz_status' => 1, 'is_recommend' => 1, 'u.role_id' => 1, 'u.id' => ['neq', $user_id]])
                    ->limit(20)
                    ->select();

                if ($list) {
                    foreach ($list as &$v) {
                        $v['username'] = getRealName($v['id']);
                        $v['avatar'] = doAvatar($v['avatar']);
                        $v['hobby'] = $v['hobby'] && $v['hobby'] != 'null' ? json_decode($v['hobby'], true) : [];
                        $v['hobby_str'] = implode('、', $v['hobby']);
                        $v['age'] = $v['age'] ? : (calculateAge($v['birth_date']) ? calculateAge($v['birth_date']) : '-');
                        $v['residence'] = $v['residence'] ? : '-';

                        $xm_arr = [
                            $v['requirement_marital_status'], $v['requirement_age'], $v['requirement_height'], $v['requirement_annual_income'], $v['requirement_buying_status']
                        ];
                        $v['xm_str'] = implode('、', array_filter($xm_arr));
                    }
                    apiReturn(4, '获取数据成功', $list);
                } else {
                    apiReturn(2, '暂无更多数据');
                }
            } else {
                apiReturn(2, '暂无更多数据');
            }
        }

    }

    /**
     * 服务列表
     * */
    public function serviceList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'] ? : 0;

        $where['status'] = 1;
        if ($user_id > 0) {
            $role_id = Db::name('user')->where(['id' => $user_id])->value('role_id');
            if ($role_id > 0) {
                $where['role_id'] = ['IN', [0, intval($role_id)]];
            } else {
                $where['role_id'] = 0;
            }
        } else {
            $where['role_id'] = 0;
        }

        $list = Db::name('service')->where($where)->field('id,img,price')->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['img'] = getPicture($v['img']);
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无数据');
        }
    }

    /**
     * 服务详情
     * */
    public function serviceDetail()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '服务ID缺失');

        $info = Db::name('service')->field('id,name,price,content')->where(['id' => $id])->find();
        if ($info) {
            $info['content'] = doEditorContent($info['content']);

            $time = time();
            // 查询是否有可用优惠券信息
            $coupon_price = Db::name('coupon')->where(['service_id' => $id, 'status' => 1])->whereTime('start_time', '<=', $time)->whereTime('end_time', '>=', $time)->max('price');
            $coupon_price = $coupon_price ? : 0;

            if ($info['price'] <= $coupon_price) apiReturn(2, '数据加载错误，请稍后再试~');

            $data = [
                'info' => $info,
                'coupon_price' => $coupon_price
            ];

            apiReturn(1, '获取数据成功', $data);
        } else {
            apiReturn(2, '服务不存在或已删除');
        }
    }

    /**
     * 开通服务
     * */
    public function openService()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $service_id = $input['service_id'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($service_id)) apiReturn(2, '服务ID缺失');
        $user_info = Db::name('user')->field('id,openid')->where(['id' => $user_id])->find();
        if (empty($user_info) || !$user_info['openid']) apiReturn(2, '用户信息有误');

        $rz_status = Db::name('user_details')->where('user_id', $user_id)->value('rz_status');
        if ($rz_status == 0) apiReturn(4, '未认证');

        $service_info = Db::name('service')->where(['id' => $service_id])->find();
        if (empty($service_info) || !$service_info['name'] || !$service_info['price']) apiReturn(2, '服务信息有误');

        // 查看该用户已开通的最高等级会员
        $user_service_info = Db::name('user_service')->where(['user_id' => $user_id, 'expire_time' => ['gt', time()]])->order('price desc')->find();
        if ($service_info['price'] < $user_service_info['price'] && $service_info['use_day'] > 0) apiReturn(2, '您已开通更高等级会员，无需再次开通');

        $time = time();
        if ($service_info) {
            // 查询是否有可用优惠券信息
            $coupon_info = Db::name('coupon')->where(['service_id' => $service_id, 'status' => 1])->whereTime('start_time', '<=', $time)->whereTime('end_time', '>=', $time)->order('price desc')->find();

            // 生成待支付订单
            $order_sn = 'SN' . date('YmdHis', $time) . mt_rand(1000, 9999);
            $pay_price = $service_info['price'] - ($coupon_info['price'] ? : 0);
            $pay_price = $pay_price > 0 ? $pay_price : 0;
            $data = [
                'user_id' => $user_id,
                'order_sn' => $order_sn,
                'service_id' => $service_info['id'],
                'service_name' => $service_info['name'],
                'service_price' => $service_info['price'],
                'service_rate' => $service_info['rate'],
                'service_use_day' => $service_info['use_day'],
                'service_look_count' => $service_info['look_count'],
                'coupon_name' => $coupon_info['name'] ? $coupon_info['name'] : '',
                'coupon_price' => $coupon_info['price'] ? $coupon_info['price'] : '',
                'pay_price' => $pay_price,
                'create_time' => $time
            ];
            Db::name('order')->insert($data);

            Loader::import('wxsdk\wxPay', EXTEND_PATH);
            $obj = new \wxPay();
            //调用示例（最后两个参数为可选参数）
            $pay_data = $obj->jsApi($user_info['openid'], $pay_price, $order_sn, '服务开通', getHost() . '/Index/Notify/notice');

            if ($pay_data) {
                $data = [
                    'order_sn' => $order_sn,
                    'pay_data' => $pay_data
                ];
                Db::commit();
                apiReturn(1, '获取支付信息成功', $data);
            } else {
                Db::rollback();
                apiReturn(2, '系统繁忙，请稍后再试~');
            }
        }
    }

    public function orderTest()
    {
        $list = Db::name('order')->where(['pay_time' => ['gt', 0]])->order('pay_time asc')->select();
        $data = [];
        foreach ($list as $v) {
            $data[] = [
                'user_id' => $v['user_id'],
                'name' => $v['service_name'],
                'price' => $v['service_price'],
                'create_time' => $v['pay_time']
            ];
        }
        Db::name('user_service')->insertAll($data);
    }

    public function getTips()
    {
        $input = Request()->param();

        $type = $input['type'] ? : 1;
        switch ($type) {
            case 1:
                $tips = C('DETAILS_TIPS');
                break;
            case 2:
                $tips = C('CHAT_TIPS');
                break;
            case 3:
                $tips = C('RZ_TIPS');
                break;
            default:
                $tips = '请联系客服';
                break;
        }

        apiReturn(1, '获取数据成功', $tips);
    }

    /**
     * 最新资讯
     * */
    public function articleList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'] ? : 0;
        $pagesize = $input['pagesize'] ? : 4;

        $role_id = Db::name('user')->where(['id' => $user_id])->value('role_id');

        $in_where = [0, $role_id ? : 0];

        $where['role_id'] = ['IN', $in_where];

        $list = Db::name('article')->field('id,title')->where($where)->order('id asc')->limit($pagesize)->select();
        if ($list) {
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无数据');
        }
    }

    /**
     * 分类消息列表
     * */
    public function msgList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $user_tags = Db::name('user')->where(['id' => $user_id])->value('msg_tags');
        $user_tags = $user_tags ? json_decode($user_tags, true) : [];

        if ($user_tags) {
            $list = Db::name('msg')->where(['user_id' => ['IN', [0, $user_id]]])
                ->where(function ($query) use ($user_tags) {
                    $query->where('tag', '')->whereOr('tag', 'IN', $user_tags);
                })
                ->page($page, $pagesize)->order('id desc')->select();
        } else {
            $list = Db::name('msg')->where(['user_id' => ['IN', [0, $user_id]], 'tag' => ''])->page($page, $pagesize)->order('id desc')->select();
        }

        if ($list) {
            foreach ($list as &$v) {
                $v['create_time'] = timeFormat($v['create_time'], 'Y-m-d H:i');
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }

    /**
     * 消息详情
     * */
    public function msgDetail()
    {
        $input = Request()->param();

        $id = $input['id'];
        $user_id = $input['user_id'];

        if (empty($id)) apiReturn(2, '消息ID缺失');
        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $info = Db::name('msg')->field('id,title,content,read_user,create_time')->where(['id' => $id])->find();
        if ($info) {
            $info['content'] = doEditorContent($info['content']);
            $info['create_time'] = timeFormat($info['create_time'], 'Y.m.d H:i');

            Db::name('msg')->where(['id' => $id])->setInc('look_count');

            $is_read = in_array($user_id, explode(',', $info['read_user'])) ? true : false;
            if (!$is_read) Db::name('msg')->where(['id' => $id])->setField('read_user', $info['read_user'] ? $info['read_user'] . ',' . $user_id : $user_id);

            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '消息不存在或已删除');
        }
    }

    /**
     * 我的收益详情
     * */
    public function userProfit()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        // 自己消费总额
        $me_all_consume = $this->getMeConsume($user_id);

        // 总累计销售额 = 我和我的所有下线的消费统计
        $all_consume = $me_all_consume + action('Algorithm / Algorithm / allConsume', ['user_id' => $user_id]);
        /**
         * 个人零售销售额 = 自己消费总额中除去自己首次消费金额
         * */
        // 自己首次消费金额
        $first_consume = Db::name('order')->where(['user_id' => $user_id, 'is_pay' => 1, 'complete_time' => ['neq', 0]])->order('id asc')->value('pay_price');
        // 个人零售销售额 = 自己消费总额 - 自己首次消费金额
        $me_consume = sprintf(' % .2f', $me_all_consume - $first_consume);

        $profit_where = [
            'user_id' => $user_id,
            'status' => ['neq', -1],
            'type' => ['IN', [1, 2, 3]]
        ];
        // 总累计收益
        $all_profit = Db::name('profit')->where($profit_where)->sum('price');
        // 可用收益
        $normal_profit = Db::name('user')->where(['id' => $user_id])->value('all_profit');
        // 冻结收益
        $frozen_profit = Db::name('profit')->where($profit_where)->where(['status' => 1])->sum('price');

        $info = [
            'all_consume' => sprintf(' % .2f', $all_consume),
            'me_consume' => sprintf(' % .2f', $me_consume),
            'all_profit' => sprintf(' % .2f', $all_profit),
            'normal_profit' => sprintf(' % .2f', $normal_profit),
            'frozen_profit' => sprintf(' % .2f', $frozen_profit),
        ];

        apiReturn(1, '获取数据成功', $info);
    }

    /**
     * 收益明细
     * */
    public function profitList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $profit_where = [
            'user_id' => $user_id,
            'status' => 1
        ];
        $profit_list = Db::name('profit')->field('id,type,profit,desc,update_time')->where($profit_where)->order('create_time desc')->page($page, $pagesize)->select();
        if ($profit_list) {
            foreach ($profit_list as &$v) {
                $v['profit'] = $v['profit'] > 0 ? ' + ' . sprintf(' % .2f', $v['profit']) : sprintf(' % .2f', $v['profit']);
                $v['update_time'] = timeFormat($v['update_time'], 'Y年m月d日');
            }
            apiReturn(1, '获取数据成功', $profit_list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }

    /**
     * 提现记录
     * */
    public function withdrawList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $list = Db::name('withdraw')->field('id,real_price price,type,status,create_time')->where(['user_id' => $user_id])->order('create_time desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['desc'] = $v['status'] == 1 ? '提现到' . ($v['type'] == 1 ? '微信钱包' : '银行卡') : '提现审核失败';
                $v['change'] = $v['status'] == 1 ? 'plus' : 'minus';
                $v['create_time'] = timeFormat($v['create_time']);
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }

    /**
     * 申请提现
     * */
    public function applyWithdraw()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $price = $input['price'];
        $real_name = $input['real_name'];
        $bank_num = $input['bank_num'];
        $bank_name = $input['bank_name'];
        $type = $input['type'] ? : 1;// 1：提现到银行卡，2：提现到微信零钱

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($price)) apiReturn(2, '请输入提现金额');
        if ($type == 1) {
            if (empty($real_name)) apiReturn(2, '请输入账户名');
            if (empty($bank_num)) apiReturn(2, '请输入账号');
            if (empty($bank_name)) apiReturn(2, '请输入开户行');
        }

        $time = time();

        Db::startTrans();
        try {
            $user_info = Db::name('user')->where(['id' => $user_id])->find();

            $order_sn = uniqid(); //订单号

            if ($type == 2) {
                if (empty($user_info['openid'])) apiReturn(2, 'openid缺失');

                // 提现到微信零钱
                $mchid = C('MCH_ID');          //微信支付商户号 PartnerID 通过微信支付商户资料审核后邮件发送
                $appid = C('XCX_APPID');       //微信支付申请对应的公众号的APPID
                $appKey = C('XCX_SECRET');     //微信支付申请对应的公众号的APP Key
                $apiKey = C('MCH_KEY');        //https://pay.weixin.qq.com 帐户设置-安全设置-API安全-API密钥-设置API密钥

                Loader::import('weixinPay\weixinPay-master\transfers', EXTEND_PATH);
                $obj = new \WxpayService($mchid, $appid, $appKey, $apiKey);

                $obj->createJsBizPackage($user_info['openid'], $price, $order_sn, $real_name);

                $data = [
                    'user_id' => $user_id,
                    'order_sn' => $order_sn,
                    'profit' => $price,
                    'type' => 2,
                    'create_time' => $time
                ];
                $withdraw_id = Db::name('withdraw')->insertGetId($data);
            } else {
                if (empty($real_name) || $real_name == 'undefined') apiReturn(2, '请输入账户名');
                if (empty($bank_num) || $bank_num == 'undefined') apiReturn(2, '请输入账号');
                if (empty($bank_name) || $bank_name == 'undefined') apiReturn(2, '请输入开户行');

                // 申请提现到银行卡
                $data = [
                    'user_id' => $user_id,
                    'order_sn' => $order_sn,
                    'profit' => $price,
                    'type' => 1,
                    'real_name' => $real_name,
                    'bank_num' => $bank_num,
                    'bank_name' => $bank_name,
                    'create_time' => $time
                ];
                $withdraw_id = Db::name('withdraw')->insertGetId($data);
            }

            $profit_data = [
                'user_id' => $user_id,
                'withdraw_id' => $withdraw_id,
                'profit' => 0 - $price,
                'desc' => '提现申请审核中',
                'type' => 2,
                'status' => 1,
                'update_time' => $time,
                'create_time' => $time
            ];
            Db::name('profit')->insert($profit_data);

            Db::name('user')->where(['id' => $user_id])->setDec('profit', $price);

            Db::commit();
            apiReturn(1, '申请提现成功');
        } catch (\Exception $e) {
            Db::rollback();
            apiReturn(2, '申请提现失败');
        }
    }

    /**
     * 订单列表
     * */
    public function orderList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $status = $input['status'] ? : 0;
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $where['user_id'] = $user_id;
        $where['is_del'] = 0;
        if ($status) $where['status'] = $status;
        $list = Db::name('order')->field('id,order_sn,pay_price,status')->where($where)->order('create_time desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['status_desc'] = doOrderStatus($v['status']);

                $goods_list = Db::name('vice_order')->field('id,img,name,price,count,sku_id')->where(['order_id' => $v['id']])->select();
                if ($goods_list) {
                    foreach ($goods_list as &$val) {
                        $val['img'] = getPicture($val['img']);
                        if ($sku_list = getSkuName(explode('-', $val['sku_id']))) $val['sku'] = implode('，', array_column($sku_list, 'name'));
                    }
                    $v['goods_list'] = $goods_list;
                }
            }

            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }

    /**
     * 订单详情
     * */
    public function orderDetail()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '订单ID缺失');

        $info = Db::name('order')->field('id,order_sn,all_price,freight_price,coupon_id,remark,pay_price,status,pay_type,express_id,send_num,get_username,get_mobile,get_province,get_city,get_area,get_address,create_time')->where(['id' => $id])->find();
        if ($info) {
            $info['create_time'] = timeFormat($info['create_time'], 'Y.m.d H:i:s');
            $info['status_desc'] = doOrderStatus($info['status']);

            $coupon_price = 0;
            if ($coupon_id = $info['coupon_id']) $coupon_price = Db::name('user_coupon')->where(['id' => $coupon_id])->value('face_price');
            $info['coupon_price'] = sprintf(' % .2f', $coupon_price);

            if ($express_id = $info['express_id']) $info['express_name'] = Db::name('express')->where(['id' => $express_id])->value('name');

            $goods_list = Db::name('vice_order')->field('id,goods_id,img,name,price,count,sku_id,gift_ids')->where(['order_id' => $id])->select();
            if ($goods_list) {
                foreach ($goods_list as &$val) {
                    $val['img'] = getPicture($val['img']);
                    if ($sku_list = getSkuName(explode('-', $val['sku_id']))) $val['sku'] = implode('，', array_column($sku_list, 'name'));

                    $gift_list = [];
                    if ($val['gift_ids']) $gift_list = Db::name('goods_gift')->field('id,gift_img,gift_name,gift_price')->where(['id' => ['IN', $val['gift_ids']], 'is_del' => 0, 'start_date' => ['elt', date('Y-m-d')], 'end_date' => ['egt', date('Y-m-d')]])->select();
                    if ($gift_list) {
                        foreach ($gift_list as &$value) {
                            $value['gift_img'] = getPicture($value['gift_img']);
                        }
                    }
                    $val['gift_list'] = $gift_list;
                }

                $info['goods_list'] = $goods_list;
            }

            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '订单不存在或已删除');
        }
    }

    /**
     * 保存用户信息
     * */
    public function saveUserInfo()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $avatar = $input['avatar'];
        $username = $input['username'];
        $gender = $input['gender'];
        $mobile = $input['mobile'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($avatar)) apiReturn(2, '请上传头像');
        if (empty($username)) apiReturn(2, '请输入昵称');

        $info = Db::name('user')->where(['id' => $user_id])->find();

        if ($info) {
            $data = [
                'avatar' => $avatar,
                'username' => $username,
                'gender' => $gender,
                'mobile' => $mobile,
                'update_time' => time()
            ];

            $res = Db::name('user')->where(['id' => $user_id])->update($data);
            if ($res) {
                apiReturn(1, '保存成功');
            } else {
                apiReturn(2, '保存失败');
            }
        } else {
            apiReturn(2, '用户不存在或已删除');
        }
    }

    /**
     * 关于我们
     * */
    public function aboutUs()
    {
        $content = Db::name('about_us')->where(['id' => 1])->value('content');

        $content = doEditorContent($content);

        apiReturn(1, '获取数据成功', $content);
    }


    // 有头像的且未认证的用户全部改成已认证
    public function doUserRz()
    {
        $list = Db::name('user')->where(['avatar' => ['gt', 0]])->select();
        if ($list) {
            foreach ($list as &$v) {
                Db::name('user_details')->where(['user_id' => $v['id'], 'rz_status' => 0])->setField('rz_status', 1);
            }
        }
    }
}
